package com.hj.service.fileserver.impl;

import java.io.*;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.artofsolving.jodconverter.util.PlatformUtils;
import org.springframework.stereotype.Service;

import com.hj.service.fileserver.FileServer;
import com.hj.util.FileUniqueIdUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author dehui dou
 * @date 2020/10/3 18:02
 * @description 当前项目所在系统作为文件服务器
 */
@Service("localServerImpl")
public class LocalServerImpl implements FileServer {
    /*
     * windows系统存储目录
     */
    private static final String WIN_SERVER_PATH = "D:/data/fileserver_home/";
    /*
     * linux系统存储目录
     */
    private static final String MAC_SERVER_PATH = "/data/fileserver_home/";
    /*
     * mac系统存储目录,暂不支持
     */
    private static final String LINUX_SERVER_PATH = "";
    private static String SYSTEM_SERVER_HOME = "";

    /**
     * @author dehui dou
     * @description 文件上传
     * @param file
     * @param fileExtName
     * @param params
     * @return java.lang.String
     */
    @Override
    public String upload(MultipartFile file, String fileExtName, Map<String, String> params) {
        String fileUniqueId = FileUniqueIdUtils.getFileUniqueId(null);
        String fastdfsFileId = String.format("%s.%s", fileUniqueId, fileExtName);
        File fastdfsfile = new File(SYSTEM_SERVER_HOME + fastdfsFileId);
        try {
            OutputStream os = new FileOutputStream(fastdfsfile);
            os.write(file.getBytes());
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fastdfsFileId;
    }

    /**
     * @author dehui dou
     * @description 文件下载
     * @param fileId
     * @return byte[]
     */
    @Override
    public byte[] download(String fileId) {
        File file = new File(SYSTEM_SERVER_HOME + fileId);
        byte[] fileData = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            fileData = IOUtils.toByteArray(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileData;
    }

    /**
     * @author dehui dou
     * @description 初始化文件路径
     */
    public void initPath() {
        if (PlatformUtils.isWindows()) {
            SYSTEM_SERVER_HOME = WIN_SERVER_PATH;
        } else if (PlatformUtils.isMac()) {
            SYSTEM_SERVER_HOME = MAC_SERVER_PATH;
        } else {
            SYSTEM_SERVER_HOME = LINUX_SERVER_PATH;
        }
        File file = new File(SYSTEM_SERVER_HOME);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}
